#!/usr/bin/env ruby

def exitWithWarning
  puts "Please pass the correct parameters:"
  puts "First argument: The parent directory"
  puts "Second argument (optional): The target directory for a copy"
  exit()
end

if ARGV[0] != nil && File.directory?(ARGV[0])
  Dir.chdir(ARGV[0])
  $counter = 1
  $date = '20110101'
else
  puts ARGV
  exitWithWarning()
end

if ARGV.length == 2
  if File.directory?(ARGV[1])
    $targetdir = ARGV[1]
  else
    exitWithWarning()
  end
end

def increaseDate()
  day = $date[-2..-1].to_i
  day += 1
  $date = $date[0..-3] + "%02d" % day
  $counter = 1
end

def timestamp
  hours = $counter / 60
  minutes = $counter % 60
  stamp = "#{$date}#{"%02d" % hours}#{"%02d" % minutes}"
  $counter += 1
  increaseDate() if $counter == 1439 # 1439 -> 23:59
  return stamp
end

def copyToDestination(filename)
  if File.directory?(filename)
    Dir.mkdir(File.join($targetdir, filename))
  else
    targetfile = File.join($targetdir, filename)
    command = "cp --preserve=all \"#{filename}\" \"#{targetfile}\""
    puts command
    `#{command}`
  end
end

def orderByDate(dir)
  Dir.entries(dir).sort{|x,y| x.downcase <=> y.downcase}.each do |entry|
    unless entry[0] == '.'
      filename = File.join(dir, entry)
      command = "touch -t #{timestamp()} \"#{filename}\""
      puts command
      `#{command}`
      copyToDestination(filename) if $targetdir
      orderByDate(filename) if File.directory?(filename)
    end
  end
end

# pass the current directory (see Dir.chdir)
orderByDate('.')
